//
//  LoginViewController.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/8/19.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import FBSDKLoginKit
import RxSwift
import GoogleSignIn

class LoginViewController: BaseUIViewController {
    
    enum LoginType {
        case login
        case bind(id: String, email: String?)
    }
    
    let emailField = LoginTextField()
    let codeField = LoginTextField()
    let getCodeButton = SendCodeButton()
    let loginButton = UIButton()
    
    let manager = LoginManager()
    let viewModel: LoginViewModel
    
    let type: LoginType
    
    init(type: LoginType) {
        self.type = type
        viewModel = LoginViewModel(id: type.id)
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupView()
        bindViewModel()
        
        switch type {
        case .login:
            self.emailField.textField.text = AppCache.shared.object(for: APPUserDefault.self).lastLoginEmail
            self.emailField.textField.sendActions(for: .editingChanged)
        case .bind(_, _):
            break
        }
    }
    
    func setupView() {
        let backgroundImage = UIImageView()
        backgroundImage.config
            .imageName("login_background")
            .addTo(view)
            .makeConstraints { (make) in
                make.left.top.right.equalTo(0)
                make.height.equalTo(backgroundImage.snp.width).multipliedBy(0.69)
        }
        
        let foregroundView = UIView().config
            .backgroundColor(.white)
            .cornerRadius(5)
            .shadowColor(.black)
            .shadowRadius(10)
            .shadowOffset(.zero)
            .shadowOpacity(0.1)
            .addTo(view)
            .makeConstraints { (make) in
                make.left.equalTo(15)
                make.centerX.equalToSuperview()
                make.top.equalTo(backgroundImage.snp.bottom).offset(-70)
        }.view
        
        let titleLabel = UILabel().config
            .font(UIFont.systemFont(ofSize: 16, weight: .medium))
            .textColor(#colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1))
            .text(type.title)
            .addTo(foregroundView)
            .makeConstraints { (make) in
                make.top.equalTo(0)
                make.height.equalTo(60)
                make.centerX.equalToSuperview()
        }.view
        
        emailField.config
            .image(AppIcon.image("", size: 25, color: #colorLiteral(red: 0.8274509804, green: 0.8274509804, blue: 0.8274509804, alpha: 1)))
            .placeHolder("请输入邮箱".localized)
            .addTo(foregroundView)
            .extra{ [weak self] in
                if let email = self?.type.email {
                    $0.text = email
                }
        }.makeConstraints { (make) in
                make.left.equalTo(20)
                make.right.equalTo(-20)
                make.top.equalTo(titleLabel.snp.bottom)
                make.height.equalTo(45)
        }
        
        codeField.config
            .image(AppIcon.image("", size: 25, color: #colorLiteral(red: 0.8274509804, green: 0.8274509804, blue: 0.8274509804, alpha: 1)))
            .placeHolder("请输入验证码".localized)
            .addTo(foregroundView)
            .makeConstraints { (make) in
                make.left.equalTo(20)
                make.right.equalTo(-20)
                make.top.equalTo(emailField.snp.bottom).offset(10)
                make.height.equalTo(45)
        }
        
        getCodeButton.config
            .title("获取邮箱验证码".localized)
            .addTo(codeField)
            .makeConstraints { (make) in
                make.right.equalTo(-20)
                make.centerY.equalToSuperview()
                make.height.equalTo(26)
        }
        
        loginButton.config
            .backgroundImage(UIImage.imageWithColor(APPConfig.baseColor))
            .clipsToBounds(true)
            .titleColor(.white)
            .cornerRadius(5)
            .title(type.buttonTitle)
            .font(UIFont.systemFont(ofSize: 16, weight: .medium))
            .addTo(foregroundView)
            .makeConstraints { (make) in
                make.top.equalTo(codeField.snp.bottom).offset(20)
                make.left.equalTo(20)
                make.height.equalTo(50)
                make.centerX.equalToSuperview()
        }
        
        let linkLabel = UILabel().config
            .fontSize(12)
            .textColor(#colorLiteral(red: 0.6941176471, green: 0.6941176471, blue: 0.6941176471, alpha: 1))
            .numberOfLines(0)
            .isUserInteractionEnabled(true)
            .addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(showUrl)))
            .addTo(foregroundView)
            .makeConstraints { (make) in
                make.centerX.equalTo(self.view.snp.centerX)
                make.bottom.equalTo(-15)
                make.left.greaterThanOrEqualTo(30)
                make.top.equalTo(loginButton.snp.bottom).offset(20)
        }.view
        
        let linkText = "用户协议和隐私政策".localized
        let text = NSMutableAttributedString.init(string: "点击登录按钮代表您已同意".localized +  "  " + linkText)
        text.setTextColor(UIColor.init(red: 78.0 / 255.0, green: 123.0 / 255.0, blue: 179.0 / 255.0, alpha: 1), text: linkText)
        linkLabel.attributedText = text
        
        let hasWxApp = WXApi.isWXAppInstalled()
        let isChina = UIDevice.current.isZhHans
        var showThirdLogin = true
        if !hasWxApp && isChina {
            showThirdLogin = false
        }
        
        let sepator = UIView().config
            .isHidden(!type.isLogin || !showThirdLogin)
            .backgroundColor(#colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1))
            .addTo(view)
            .makeConstraints { (make) in
                make.bottom.equalTo(-UIApplication.shared.bottomSafeDistance - 110)
                make.centerX.equalToSuperview()
                make.width.equalTo(250)
                make.height.equalTo(1)
        }.view
        
        UILabel().config
            .isHidden(!type.isLogin || !showThirdLogin)
            .backgroundColor(.white)
            .textAlignment(.center)
            .font(.systemFont(ofSize: 12, weight: .medium))
            .textColor(#colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1))
            .text("  " + "一键登录".localized + "  ")
            .addTo(view)
            .makeConstraints { (make) in
                make.centerY.equalTo(sepator.snp.centerY)
                make.centerX.equalToSuperview()
        }
        
        let bottonContainer = UIStackView().config
            .isHidden(!type.isLogin)
            .addTo(view)
            .extra {
                $0.axis = .horizontal
                $0.distribution = .equalCentering
                $0.spacing = 30
                $0.alignment = .center
        }.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-UIApplication.shared.bottomSafeDistance)
            make.top.equalTo(sepator.snp.bottom)
        }.view
        
        /*
        if hasWxApp && isChina {
            UIButton().config
            .image(#imageLiteral(resourceName: "wechat"))
            .addTarget(self, action: #selector(weChatButtonClick), for: .touchUpInside)
            .extra{ bottonContainer.addArrangedSubview($0) }
        }
        
        if !isChina {
            UIButton().config
                .image(#imageLiteral(resourceName: "facebook"))
                .addTarget(self, action: #selector(facebookButtonClick), for: .touchUpInside)
                .extra{ bottonContainer.addArrangedSubview($0) }
            
            UIButton().config
                .image(#imageLiteral(resourceName: "google"))
                .addTarget(self, action: #selector(googleButtonClick), for: .touchUpInside)
                .extra{ bottonContainer.addArrangedSubview($0) }
        }*/
    }
    
    @objc func showUrl() {
        let vc = BaseWebViewController.init(url: APPConfig.protocolUrl)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func bindViewModel() {
        let input = LoginViewModel.Input.init(email: emailField.rx.text,
                                              code: codeField.rx.text,
                                              getCodeTap: getCodeButton.rx.tap,
                                              loginTap: loginButton.rx.tap)
        let output = viewModel.transform(input)
        
        output.codeButtonState
            .map{ $0.title }
            .bind(to: getCodeButton.rx.title(for: .normal))
            .disposed(by: rx.disposeBag)
        
        output.codeButtonState
            .map{ $0.isEnabled }
            .bind(to: getCodeButton.rx.isEnabled)
            .disposed(by: rx.disposeBag)
        
        output.loginResult
            .filterNil()
            .subscribe(onNext: { [weak self] (model) in
                self?.getUserInfo(model: model)
            }).disposed(by: rx.disposeBag)
        
        NotificationCenter.default.rx.notification(.weChatLoginSuccess)
            .map{ $0.userInfo as? [String: String] }
            .map{ $0?["code"] }
            .filterNil()
            .flatMap {
                ApiManager.wxAuth($0).request()
                    .errorWhenCodeNot200()
                    .dataModelMap(WXInfoModel.self)
                    .trackingLoading()
                    .catchError {_ in Observable.empty() }
        }.subscribe(onNext: { [weak self] (model) in
            self?.thirdLogin(type: .wechat, appId: nil, openId: model.openId, nickname: model.nickname, userPic: model.nickname, email: nil)
        }).disposed(by: rx.disposeBag)
    }
    
    @objc func weChatButtonClick() {
        let req = SendAuthReq.init()
        req.scope = "snsapi_userinfo"
        req.state = "wx_oauth_authorization_state"
        WXApi.sendAuthReq(req, viewController: self, delegate: nil)
    }
    
    @objc func facebookButtonClick() {
        let permissions = ["public_profile", "email"]
        let parameters = ["fields": "id,name,email,first_name,last_name,gender,locale,picture"]

        manager.rx.login(permissions: permissions, from: self)
            .map{ $0.token?.userID ?? "" }
            .asObservable()
            .flatMap {
                return GraphRequest.rx.start(graphPath: $0, parameters: parameters, method: .get)
                    .asObservable()
                    .trackingLoading()
        }.subscribe(onNext: { [weak self] (result) in
            let result = result as? [String: Any] ?? [:]
            let email = result["email"] as? String
            let name = result["name"] as? String
            let id = result["id"] as? String ?? ""
            let headPic = "http://graph.facebook.com/\(id)/picture?type=large"
            self?.thirdLogin(type: .facebook, appId: nil, openId: id, nickname: name, userPic: headPic, email: email)
        }).disposed(by: rx.disposeBag)
    }
    
    @objc func googleButtonClick() {
//        GIDSignIn.sharedInstance().delegate = self
//        GIDSignIn.sharedInstance()?.uiDelegate = self
//        GIDSignIn.sharedInstance()?.signIn()
        
        GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, error in
            if (error != nil) {
                let err: NSError = error! as NSError;
                APPHud.shared.showError(status: err.localizedDescription)
            } else {
                let res: GIDSignInResult = signInResult!;
                self.thirdLogin(type: .google, appId: nil, openId: res.user.userID ?? "", nickname: res.user.profile?.name, userPic: res.user.profile?.imageURL(withDimension: 1080)?.absoluteString, email: res.user.profile?.email)
            }
        }
    }
    
    func thirdLogin(type: ThirdLoginType, appId: String?, openId: String, nickname: String?, userPic: String?, email: String?) {
        ApiManager.thirdLogin(type: type, appId: appId, openId: openId, nickname: nickname, userPic: userPic)
            .request()
            .filterCode200()
            .dataModelMap(ThirdLoginModel.self)
            .trackingLoading()
            .subscribe(onNext: { [weak self] (model) in
                if let tokenModel = model.appToken {
                    self?.getUserInfo(model: tokenModel)
                } else {
                    let vc = LoginViewController.init(type: .bind(id: model.id, email: email))
                    self?.navigationController?.pushViewController(vc, animated: true)
                }
            }).disposed(by: rx.disposeBag)
    }
    
    func getUserInfo(model: LoginModel) {
        ApiManager.getUserInfo(model: model)
            .request()
            .filterCode200()
            .dataModelMap(PersonalModel.self)
            .trackingLoading()
            .subscribe(onNext: { [weak self] (info) in
                if info.hasPerfect {
                    AppCache.shared.updateObject(for: APPUserDefault.self) { (userDefault) in
                        userDefault.lastLoginEmail = info.email
                    }
                    APPUser.shared.state = .login(model)
                    UIApplication.shared.keyWindow?
                        .setRootViewController(MainTabBarViewController(), type: .push)
                } else {
                    let vc = RegisterViewController(model: model, email: info.email)
                    self?.navigationController?.pushViewController(vc, animated: true)
                }
            }).disposed(by: rx.disposeBag)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.view.endEditing(true)
    }
    
    override func backButtonStyle() -> BackButtonStyle {
        if self.type.isLogin {
            return .none
        }
        return .normal
    }
    
    override func navigationBarStyle() -> NavigationBarStyle {
        return .clearColor
    }
}

//extension LoginViewController: GIDSignInDelegate, GIDSignInUIDelegate {
//
//    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
//        if let error = error {
//            APPHud.shared.showError(status: error.localizedDescription)
//        } else if let user = user {
//            self.thirdLogin(type: .google, appId: nil, openId: user.userID, nickname: user.profile.name, userPic: user.profile.imageURL(withDimension: 1080)?.absoluteString, email: user.profile.email)
//        }
//    }
//
//}

extension LoginViewController.LoginType {
    
    var isLogin: Bool {
        switch self {
        case .login: return true
        default: return false
        }
    }
    
    var id: String? {
        switch self {
            case .bind(let id, _): return id
        default: return nil
        }
    }
    
    var email: String? {
        switch self {
            case .bind(_, let email): return email
        default: return nil
        }
    }
    
    var title: String {
        switch self {
        case .login:
            return "邮箱 验证登录/注册".localized
        case .bind(_, _):
            return "绑定邮箱".localized
        }
    }
    
    var buttonTitle: String {
        switch self {
        case .login:
            return "登录".localized
        case .bind(_, _):
            return "完成".localized
        }
    }
}
